from app.extension.database.sqlalchemy import sqla_db as db
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime
from datetime import datetime


class UserModel(db.Model):

    """用户模型"""

    __tablename__ = 'tb_user'
    id = db.Column(db.Integer, primary_key=True)
    tel = db.Column(db.String(15))
    nick_name = db.Column(db.String(80))
    city = db.Column(db.String(80))
    country = db.Column(db.String(80))
    gender = db.Column(db.Boolean, default=False, comment='0女 1男')
    create_time = db.Column(db.DateTime, default=datetime.now)
    delete_time = db.Column(db.DateTime)
    openid = db.Column(db.String(80), unique=True, nullable=False)
    type = db.Column(db.Integer, default=1, comment='用户的类别: 1 普通用户 2 管理员')
    store_id = db.Column(db.Integer, comment='用户对应的商铺信息')

    def __init__(self, openid):
        self.openid = openid

    def update(self, data):
        nick_name = data.get('nick_name')
        tel = data.get('tel')
        gender = data.get('gender')
        self.nick_name = nick_name or self.nick_name
        self.tel = tel or self.tel
        if gender is not None:
            self.gender = bool(gender)